package com.jswlw.controller.distributor;

import com.jswlw.controller.BaseController;
import com.jswlw.entity.biz.DevInfo;
import com.jswlw.entity.biz.Distributor;
import com.jswlw.service.biz.DevInfoService;
import com.jswlw.service.biz.DistributorService;
import com.jswlw.web.manager.SessionDistributorManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * @author 吴维斌 E-mail:wuweibin0817@163.com
 * @version 创建时间：${date} ${time}
 */
@Controller
@RequestMapping("/distributor/manager")
public class DistributorManagerController extends BaseController {

    @Autowired
    DistributorService distributorService;

    @Autowired
    DevInfoService devInfoService;

    @RequestMapping("index")
    public ModelAndView index(@RequestParam("level") Integer level) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/distributor/manager/index");
        modelAndView.addObject("level", level);
        Distributor filter = new Distributor();
        filter.setParentId(SessionDistributorManager.getCurrentUser().getDistributorId());
        filter.setLevel(level);
        List<Distributor> list = distributorService.queryList(filter);
        list.forEach(distributor -> {
            DevInfo devInfoFilter=new DevInfo();
            devInfoFilter.setDistributorIds(distributorService.getChildrenIds(distributor.getId()));
            List<DevInfo> allDev=devInfoService.queryList(devInfoFilter);
            distributor.setDevInfoList(allDev);
            devInfoFilter.setOnlineStatus(1);
            distributor.setAllCount(allDev.size());
            distributor.setOnlineCount(devInfoService.queryList(devInfoFilter).size());

        });

        modelAndView.addObject("distributorList", list);
        return modelAndView;
    }

    @RequestMapping("add")
    public ModelAndView add() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/distributor/manager/add");
        modelAndView.addObject("parentId", SessionDistributorManager.getCurrentUser().getDistributorId());
        return modelAndView;
    }

    @RequestMapping(value = "/doAdd", method = RequestMethod.POST)
    @ResponseBody
    public ModelMap doLogin(Distributor distributor) {
        distributor.setParentId(SessionDistributorManager.getCurrentUser().getDistributorId());
        distributor.setLevel(SessionDistributorManager.getCurrentUser().getLevel() + 1);
        distributorService.add(distributor);
        return this.successResult("");
    }
}
